package com.xjscrm.server.common.util;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;

import java.util.HashSet;
import java.util.Set;

/**
 * 生成随机的11位id
 * @author liuqi
 * @date 2024年03月05日 15:05
 */
public class ShortChainUtils {
    private static final long MIN = 10000000000L;
    private static final long MAX_ID = 99999999999L;

    private static final long SUFFIX_ID = ((1L << 34) - 1);
    private static final long PRE_ID = (7L << 34);

    public static long creatShortId(long id) {

        // 非线性
        long tempId = swap(id, 7, 0);
        tempId = swap(tempId, 6, 1);

        // Id后34位
        long value = tempId & SUFFIX_ID;

        // Id后34位的最低八位和高1-9位交换
        value = (((value >> 8) | ((value & 255) << 26)));

        // Id前3位|Id后34位
        tempId = (tempId & PRE_ID) | value;

        // 加上最小值,
        tempId += MIN;
        if(tempId > MAX_ID){ //如果超过11位，则不添加
            tempId = tempId - MIN;
        }
        return tempId;
    }

    /**
     * xxxx xxxx xxxx x0xx xxxx xx0x xxxx xxxx|0000 0000 0000 0b00 0000 00a0
     * 0000 0000
     */
    private static long swap(long value, int x, int y) {

        return (value & (~(1 << x)) & (~(1 << y))) | (((value >> x) & 1) << y) | (((value >> y) & 1) << x);
    }

    private ShortChainUtils() {
    };

    public static void main(String[] args){
        Set set = new HashSet();
        for(int i=0;; i++) {
            Long idTemt = IdWorker.getId();
            long id = ShortChainUtils.creatShortId(idTemt);
            System.out.println(id +"---"+i + "---" + idTemt);
            if(set.contains(id)){
                System.out.println("duplicated");
                break;
            }
            set.add(id);

            if(id > 99999999999L){
                System.out.println("生错");
                return;
            }
        }
    }
}
